#include "StdAfx.h"
#include "ListModel.h"

#include <algorithm>

#include <atltime.h>

#include "FileIterator.h"

static std::wstring Trim(const std::wstring& str)
{
    for (std::wstring::const_iterator it = str.begin(); it != str.end(); it++) {
        if (iswspace(*it))
            continue;

        return std::wstring(it, str.end());
    }

    return std::wstring();
}

static bool SortLastWrite(ListItem& item1, ListItem& item2) {
    return CFileTime(item1.LastWriteTime) > CFileTime(item2.LastWriteTime);
}

static bool SortCreateTime(ListItem& item1, ListItem& item2) {
    return CFileTime(item1.CreateTime) > CFileTime(item2.CreateTime);
}

void ListModel::LoadDir( const std::wstring& dirName )
{    
    std::vector<ListItem> newItems;

    try {
        FileIterator fileIterator(dirName, _T("*.txt"));

        int i = 1;
        do {
            ListItem item;

            item.FileName = dirName + fileIterator.Get();
            
            try {
                ListItem::Init(item);
                newItems.push_back(item);
            }
            catch(...) {}

            i++;

        } while(fileIterator.Next());

        std::sort(newItems.begin(), newItems.end(), SortCreateTime);

        // for future async update?
        items = newItems;
    }
    catch(...) {
        items.clear();
    }

}

void ListModel::UpdateItem( int i )
{
    ATLASSERT( items.size() > i && i >= 0 );
    ListItem::Init( items[i] );
}